package org.nextive.android.weightapp;

import org.nextive.android.weightapp.utils.AccountsHelper;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class InitialSetup extends AccountsHelper
{
	//Constants key for preferences
	public static final String PREFERENCES_NAME = "Preferences";
	public static final String PREFERENCES_KEY_NAME = "Name";
	public static final String PREFERENCES_KEY_EMAIL = "Email";
	public static final String PREFERENCES_KEY_UNIT = "Unit";
	
	//Constants for pick contact request
	public static final int PICK_CONTACT_REQUEST = 1;
	
	private EditText editTextName;
	private EditText editTextEmail;
	private Spinner spinnerUnits;
	private Button buttonPickContact;
	private Button buttonAccountEmail;
	private Button buttonSaveSetup;
		
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
    	super.onCreate(savedInstanceState);  	
    	if (!Intent.ACTION_MAIN.equals(getIntent().getAction()) || !isPreferencesCreated())
    	{
    		setContentView(R.layout.initial_setup);
	        
	        editTextName = (EditText) findViewById(R.id.editTextName);
	        editTextEmail = (EditText) findViewById(R.id.editTextEmail);
	        
	        spinnerUnits = (Spinner) findViewById(R.id.spinnerUnits);
	        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
	                this, R.array.units, android.R.layout.simple_spinner_item);
	        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        spinnerUnits.setAdapter(adapter);
	        
	        buttonPickContact = (Button) findViewById(R.id.buttonPickContact);
	        buttonPickContact.setOnClickListener(new OnClickListener() 
	        {
				@Override
				public void onClick(View v) 
				{
					Intent contactManagerIntent = new Intent(InitialSetup.this, ContactManager.class);
					startActivityForResult(contactManagerIntent,PICK_CONTACT_REQUEST);
				}
			});
	        
	        buttonAccountEmail = (Button) findViewById(R.id.buttonAccoutEmail);
	        buttonAccountEmail.setOnClickListener(new OnClickListener() 
	        {
				@Override
				public void onClick(View v) 
				{
					selectAccountEmail();
				}
			});
	        
	        buttonSaveSetup = ((Button)findViewById(R.id.buttonSaveSetup));
	        buttonSaveSetup.setOnClickListener(new OnClickListener() 
	        {
				@Override
				public void onClick(View v) 
				{
					saveSettings();
				}
			});
	        
	        loadSettings();
    	}
    	else
    	{
    		Intent saveIntent = new Intent(InitialSetup.this, LogWeight.class);
        	startActivity(saveIntent);
        	finish();
    	}
    }
    
    private void loadSettings()
    {
    	SharedPreferences settings = getSharedPreferences(PREFERENCES_NAME, 0);
        String name = settings.getString(PREFERENCES_KEY_NAME, "");
        editTextName.setText(name);
        String email = settings.getString(PREFERENCES_KEY_EMAIL, "");
        editTextEmail.setText(email);
        int unit = settings.getInt(PREFERENCES_KEY_UNIT, 0);
        spinnerUnits.setSelection(unit);	
    }
    
    private void saveSettings()
    {
    	if (validateFields())
    	{
	    	SharedPreferences settings = getSharedPreferences(PREFERENCES_NAME, 0);
	    	SharedPreferences.Editor editor = settings.edit();
	    	String name = editTextName.getText().toString();
	    	editor.putString(PREFERENCES_KEY_NAME, name);
	    	String email = editTextEmail.getText().toString();
	    	editor.putString(PREFERENCES_KEY_EMAIL, email);
	    	int unit = spinnerUnits.getSelectedItemPosition();
	    	editor.putInt(PREFERENCES_KEY_UNIT, unit);
	    	editor.commit();
	    	
	    	Toast.makeText(InitialSetup.this, R.string.settings_saved, Toast.LENGTH_SHORT).show();
        	Intent saveIntent = new Intent(InitialSetup.this, LogWeight.class);
        	startActivity(saveIntent);
    	}	
    }
    
    private boolean isPreferencesCreated()
    {
    	SharedPreferences settings = getSharedPreferences(PREFERENCES_NAME, 0);
    	return (settings.contains(PREFERENCES_KEY_NAME) && settings.contains(PREFERENCES_KEY_EMAIL) && settings.contains(PREFERENCES_KEY_UNIT));
    }
    
    private boolean validateFields()
    {
    	if (editTextName.getText().toString().isEmpty())
    	{
    		Toast.makeText(this, R.string.name_empty, Toast.LENGTH_SHORT).show();
    		return false;
    	}
    	if (editTextEmail.getText().toString().isEmpty())
    	{
    		Toast.makeText(this, R.string.default_email_empty, Toast.LENGTH_SHORT).show();
    		return false;
    	}
    	return true;
    }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		switch (requestCode)
		{
			case PICK_CONTACT_REQUEST:
				if (resultCode == RESULT_OK)
				{
					Bundle extras = data.getExtras();
					String email = extras.getString(ContactManager.EXTRA_KEY_EMAIL);
					editTextEmail.setText(email);
				}
			break;
		}
	}
	
	private void selectAccountEmail()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(InitialSetup.this);
        builder.setTitle(R.string.select_account);
        final String [] accountsArray = new String[getAccounts().size()];
        for (int i=0; i<accountsArray.length; i++)
        {
        	accountsArray[i] = getAccounts().get(i).getName();
        }
        ArrayAdapter<String> accountsDialogAdapter = new ArrayAdapter<String>(this, R.layout.account_menu_item, accountsArray);
        builder.setAdapter(accountsDialogAdapter, new DialogInterface.OnClickListener() 
        {
            public void onClick(DialogInterface dialog, int item) 
            {
            	editTextEmail.setText(accountsArray[item]);
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
	}
}